#include "InetAddr.hpp"

#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <fstream>
// 套接字四件套
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define CONV(v) (struct sockaddr *)(v)

using namespace std;

static int gsockfd = -1;
const string gdefauttip = "47.109.203.137";
const static uint16_t gdefaultport = 8888;

class UdpServer
{
public:
    UdpServer(uint16_t port = gdefaultport)
        : _socketfd(gsockfd), _port(port), _isrunning(false)
    {
    }
    void Init() // 套接字初始化
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0); // 选择网络还是本地
        if (_socketfd < 0)                          // 如果为-1表示创建失败
        {
            cout << "创建套接字失败" << endl;
            exit(-1);
        }
        // 地址初始化
        // struct sockaddr_in local;
        InterAddr addr(gdefaultport);
        // bzero(&local, sizeof(local));
        // local.sin_family = AF_INET;
        // local.sin_port = htons(_port);                                     // 主机转网络端口
        // local.sin_addr.s_addr = INADDR_ANY;                                // 主机转网络ip
        int n = bind(_socketfd, addr.NetAddr(), addr.NetAddrLen()); // 绑定套接字与地址
        if (n == -1)
        {
            perror("1111");
            cout << "绑定失败" << endl;
        }
        cout << "bind sucess";
    }
    int count=0;
    void Start()
    {
        ofstream ofs("kq.png", ofstream::binary);
        _isrunning = true;

        while (true)
        {
            count++;
            char buffer[1024]{0};
            int defaultsize = 1024;
            struct sockaddr_in client;
            socklen_t sockaddrlen = sizeof(client);

            int n = recvfrom(_socketfd, buffer, defaultsize, 0, CONV(&client), &sockaddrlen); // 接收消息--0为阻塞等待
            if (n > 0)
            {
                uint16_t clientport = ntohs(client.sin_port);
                string clientip = inet_ntoa(client.sin_addr);
                ofs.put(buffer[0]);

                // cout<<"来自ip->"<<clientip<<"端口号->"<<clientport<<"消息:";
                // cout<<buffer<<endl;
                string echo = "插入成功";
                echo += "zgnb";

                sendto(_socketfd, echo.c_str(), echo.size(), 0, CONV(&client), sizeof(client));
            }
            if(count==17891375)
            {
                cout<<"加载完毕"<<endl;
                ofs.close();
                break;
            }

        }
        _isrunning = false;
    }

private:
    uint16_t _port;
    // string _ip;
    int _socketfd; // 创建的sokect的文件描述符
    bool _isrunning;
};